import { useState, useEffect, useRef, forwardRef } from 'react';
import './lazyload.css';

const LazyLoad = forwardRef(({
  src,
  alt = '懒加载图片',
  className = '',
}, ref) => {
  const [isLoaded, setIsLoaded] = useState(false);
  const imgRef = useRef(null);
  // 新增：存储 observer 实例引用，方便统一清理
  const observerRef = useRef(null);

  useEffect(() => {
    // 1. 初始化 observer 并存储到 ref
    observerRef.current = new IntersectionObserver(
      (entries) => {
        entries.forEach(entry => {
          if (entry.isIntersecting) {
            const img = new Image();
            img.src = src;
            img.alt = alt;
            img.onload = () => {
              setIsLoaded(true);
              // 修复1：先校验 imgRef.current 是 Element 再取消观察
              if (imgRef.current instanceof Element) {
                observerRef.current.unobserve(imgRef.current);
              }
            };
            img.onerror = () => {
              setIsLoaded(true);
              // 修复2：错误时同样校验元素
              if (imgRef.current instanceof Element) {
                observerRef.current.unobserve(imgRef.current);
              }
              console.warn(`LazyLoad组件：图片加载失败，地址：${src}`);
            };
          }
        });
      },
      { rootMargin: '200px 0px' }
    );

    // 2. 观察元素前先校验
    if (imgRef.current instanceof Element) {
      observerRef.current.observe(imgRef.current);
    }

    // 3. 组件卸载：严谨清理（先校验再操作）
    return () => {
      const observer = observerRef.current;
      const imgElement = imgRef.current;
      if (observer && imgElement instanceof Element) {
        observer.unobserve(imgElement);
      }
      // 销毁 observer 实例（彻底释放资源）
      if (observer) observer.disconnect();
    };
  }, [src, alt]);

  return (
    <div className={`lazy-load-container ${isLoaded ? 'loaded' : ''}`}>
      <div className="lazy-load-placeholder"></div>
      <img
        ref={imgRef}
        src={isLoaded ? src : ''}
        alt={alt}
        className={`lazy-load-img ${className} ${isLoaded ? 'loaded' : ''}`}
        loading="lazy"
      />
    </div>
  );
});

LazyLoad.displayName = 'LazyLoad';
export default LazyLoad;